odoo.define('lift_base.rescue_vehicle_track_map', function (require) {
    "use strict";
    var WebClient = require('web.AbstractWebClient');
    var ajax = require('web.ajax');
    var core = require('web.core');
    var Widget = require('web.Widget');
    var Model = require('web.Model');
    var session = require('web.session');
    var framework = require('web.framework');

    var form_common = require('web.form_common');
    var common_widget = require('lift_base.common_widget');

    var RescueVehicleTrackMap = form_common.FormWidget.extend({
        template:"baidu_map_template",
        init: function(field_manager, node) {
            this._super(field_manager, node);
            this.token = false;
            this.move_car_icon = new BMap.Icon("/lift_base/static/src/img/move_car.png", new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
            this.stop_car_icon = new BMap.Icon('/lift_base/static/src/img/stop_car.png', new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
            this.convertor = new BMap.Convertor();
            // this.reset_token();
        },
        start: function () {
            this._super();
            this.device_code = this.field_manager.get_field_value('GPS_code');
            this.field_manager.on("field_changed:GPS_code",this,this.change_gps_code);
            var self = this;
            common_widget.get_default_city(function (city) {
                self.city = city;
                self.init_map();
            })
        },
        change_gps_code: function () {
            this.device_code = this.field_manager.get_field_value('GPS_code');
            this.set_dynamic_position();
        },
        reset_token: function () {
            // 设置gps api的token
            var self = this;
            $.post("/api/auth/login", {'username': "zmd_gps_admin", 'password': 'p@ssw0rd'}, function (res) {
               self.token = res.data.token;
               self.set_dynamic_position();
            });
        },
        init_map: function () {
            var self = this;
            var map = new BMap.Map(self.$el[0]);
            map.centerAndZoom(self.city.name, 15);
            map.enableScrollWheelZoom(true);
            self.map = map;
            self.add_marker();
        },
        add_marker:function () {
            var self = this;
            // 给marker一个默认地址，不然会报错
            var car_marker = new BMap.Marker(self.city.name);
            self.car_marker = car_marker;
            self.map.addOverlay(car_marker);
            var rescue_vehicle_info_widget = new RescueVehicleInfoWidget(self);
            rescue_vehicle_info_widget.appendTo(self.$el);

            if (!self.token) {
                self.reset_token();
            }
            // 启动定时任务前先执行一波，不然要等很久
            // self.set_dynamic_position();
            self.set_dynamic_position_interval = setInterval(function(){self.set_dynamic_position()}, 1000 * 5);
        },
        set_dynamic_position: function () {
            var self = this;
            $.ajax({
                async: true,
                url: '/api/device/gps/list',
                type: 'POST',
                data: {
                    device_code: self.device_code
                },
                headers: {
                    'x-access-token': self.token
                },
                success: function (gps_data) {
                    if (gps_data.code == 0 && gps_data.data.length > 0) {
                        self.convertor.translate([new BMap.Point(gps_data.data[0].lng, gps_data.data[0].lat)], 1, 5, function (data) {
                            if (data.status === 0) {
                                // marker已存在，更改其position
                                self.car_marker.setPosition(data.points[0]);
                                $(".tyibs_device_code").html(gps_data.data[0].device_code);
                                $(".tyibs_address").html(gps_data.data[0].address);
                                $(".tyibs_speed").html(gps_data.data[0].speed);
                                $(".tyibs_state").html(gps_data.data[0].state);
                                self.map.panTo(data.points[0]);
                                // 修改小车车的icon
                                if (gps_data.data[0].speed > 0){
                                    //车子在动
                                    self.car_marker.setIcon(self.move_car_icon);
                                }else {
                                    //车子静止
                                    self.car_marker.setIcon(self.stop_car_icon);
                                }
                                //改变小车车方向
                                self.car_marker.setRotation(gps_data.data[0].direction);
                            }
                        });
                    }
                }
            });
        },
        destroy: function () {
            var self = this;
            // 销毁时清除interval
            window.clearInterval(self.set_dynamic_position_interval);
            this._super();
        }
    });

    // 后台车辆form表单里显示的GPS信息
    var RescueVehicleInfoWidget = Widget.extend({
        template: "baidu_map_rescue_vehicle_info",
        init: function (parent) {
            this._super(parent);
        }
    });

    var RescueVehicleMap = Widget.extend({
        template: "baidu_map_rescue_vehicle",
        init: function (parent) {
            this._super(parent);
            this.token="";
            this.car_overlay = [];
            this.move_car_icon = new BMap.Icon("/lift_base/static/src/img/move_car.png", new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
            this.stop_car_icon = new BMap.Icon('/lift_base/static/src/img/stop_car.png', new BMap.Size(25, 50),{imageSize:new BMap.Size(25,50)});
            this.convertor = new BMap.Convertor();
        },
        start: function () {
            var self = this;
            common_widget.get_default_city(function (city) {
                self.city = city;
                self.init_load();
            });
        },
        init_load: function () {
            this.init_baidu_map();
            this.reset_token();
            this.add_area_boundary();
            this.show_all_car();

            var btn_block = new RescueVehicleMapBtnBlock(this);
            btn_block.on("show_or_hide_menu", this, this.show_or_hide_menu);
            btn_block.appendTo(this.$el);

            this.init_show_or_hide_menu_text();
        },
        init_baidu_map: function () {
            var map = new BMap.Map(this.$el[0], {
                minZoom: 10,
            });
            map.centerAndZoom(this.city.name, 10);
            map.enableScrollWheelZoom(true);
            // map.addControl(new BMap.MapTypeControl());
            this.map = map;
        },
        reset_token: function () {
            // 设置gps api的token
            var self = this;
            $.post("/api/auth/login", {'username': "zmd_gps_admin", 'password': 'p@ssw0rd'}, function (res) {
               self.token = res.data.token;
            });
        },
        init_show_or_hide_menu_text: function () {
            var self = this;
            if ($(".o_sub_menu").css("display") == "none" && $("#oe_main_menu_navbar").css("display") == "none") {
                self.$(".show_or_hide_menu").html("显示菜单");
            } else {
                self.$(".show_or_hide_menu").html("隐藏菜单");
            }
        },
        show_or_hide_menu: function () {
            $(".o_sub_menu").toggle();
            $("#oe_main_menu_navbar").toggle();
            this.init_show_or_hide_menu_text();
        },
        get_areas: function () {
            //获取下所有区
            var area_model = new Model("tyibs.base.province.city.area");
            return area_model.query(['name', 'ln', 'la', 'color']).filter([['city_id', '=', this.city.is]]).all();
        },
        add_area_boundary: function () {
            //添加各区/县边界线
            var self = this;
            self.get_areas().then(function (results) {
                results.forEach(function (item) {
                    if (item.name != "开发区") {
                        self.add_single_map_polygon(self.city.name + item.name, item.id, "", "", 3, "");
                    }
                });
            });
        },
        add_single_map_polygon: function (name, id, fillColor, strokeColor, strokeWeight, angle_of_view) {
            /*
             生成单个的行政图层
             angle_of_view: 视角，city or area
             */
            var self = this;
            var bdary = new BMap.Boundary();
            // var instead_name = name == "开发区" ? "驿城区" : name;
            bdary.get(name, function (rs) {       //获取行政区域
                var count = rs.boundaries.length; //行政区域的点有多少个
                if (count === 0) {
                    return;
                }
                fillColor = fillColor != undefined ? fillColor : '';
                strokeColor = strokeColor != undefined && strokeColor != "" ? strokeColor : 'red';
                strokeWeight = strokeWeight != undefined ? strokeWeight : 1;
                for (var i = 0; i < count; i++) {
                    var ply = new BMap.Polygon(rs.boundaries[i], {
                        strokeWeight: strokeWeight, strokeColor: strokeColor,
                        fillColor: fillColor, fillOpacity: 0.8, strokeStyle: 'dashed'
                    }); //建立多边形覆盖物

                    self.map.addOverlay(ply);
                }
            })
        },
        format_undefined_data: function (data) {
            // 格式化数据
            return data && data != "undefined" && data != "false" ? data : "未知"
        },
        show_all_car: function () {
            // 显示所有车辆
            var self = this;
            if (self.token == ""){
                self.reset_token();
            }
            new Model("tyibs.base.maintenance.rescue.vehicle").query([]).filter([]).all().then(function (records) {
                self.add_car_marker(records);
                self.get_car_gps_interval = setInterval(function () {
                    self.add_car_marker(records);
                }, 1000 * 5)
            })
        },
        add_car_marker: function (records) {
            var self =this;
            $.ajax({
                url: '/api/device/gps/current',
                type: 'POST',
                headers: {
                    'x-access-token': self.token
                },
                success: function (cars_gps_data) {
                    if (cars_gps_data.code == 0){
                        records.forEach(function (car) {
                            var car_gps = cars_gps_data.data.filter(function (item) {
                                return car.GPS_code == item.device_code;
                            });
                            if (car_gps.length > 0){
                                self.convertor.translate([new BMap.Point(car_gps[0].position.lng, car_gps[0].position.lat)], 1, 5, function (data) {
                                    if(data.status === 0) {
                                        var exist_marker = self.car_overlay.filter(function (marker) {
                                            return marker.device_code == car.GPS_code;
                                        });
                                        if (exist_marker.length > 0){
                                            // marker已存在，更改其position
                                            exist_marker[0].setPosition(data.points[0]);
                                            $(".address_" + car_gps[0].device_code).html(car_gps[0].position.address);
                                            $(".state_" + car_gps[0].device_code).html(car_gps[0].position.state);
                                            $(".speed_" + car_gps[0].device_code).html(car_gps[0].position.speed);
                                            self.set_car_state(exist_marker[0], car_gps[0]);
                                        }else {
                                            // marker不存在，创建marker
                                            var marker = new BMap.Marker(data.points[0]);
                                            var label = new BMap.Label(car.code + '-' + car.manager, {offset   : new BMap.Size(-35, -20)});
                                            label.setStyle({
                                                "color": "red",
                                                "max-width": "none"
                                            });
                                            marker.setLabel(label);
                                            marker.device_code = car.GPS_code;
                                            marker.addEventListener('click', function (e) {
                                                var info_window_widget = new InfoWindow(self, car.id,
                                                    car.enterprise_id[1],
                                                    self.format_undefined_data(car.code),
                                                    self.format_undefined_data(car.GPS_code),
                                                    self.format_undefined_data(car.GPS_mobile),
                                                    self.format_undefined_data(car.manager),
                                                    self.format_undefined_data(car.manager_mobile),
                                                    self.format_undefined_data(car_gps[0].position.address),
                                                    self.format_undefined_data(car_gps[0].position.state),
                                                    self.format_undefined_data(car_gps[0].position.speed)
                                                );
                                                info_window_widget.appendTo(self.$el);
                                                var info_window = new BMap.InfoWindow(info_window_widget.$el[0]);
                                                marker.openInfoWindow(info_window);
                                            });

                                            self.set_car_state(marker, car_gps[0]);
                                            self.map.addOverlay(marker);
                                            self.car_overlay.push(marker);
                                        }
                                    }
                                });
                            }
                        })
                    }else{
                        console.error(cars_gps_data.msg);
                    }

                }
            });
        },
        set_car_state: function (marker,car_gps) {
            var self = this;
            // 修改小车车的icon
            if (car_gps.position.speed > 0){
                //车子在动
                marker.setIcon(self.move_car_icon);
            }else {
                //车子静止
                marker.setIcon(self.stop_car_icon);
            }
            //改变小车车方向
            marker.setRotation(car_gps.position.direction);
        },
        destroy:function () {
            // 销毁时清除定时方法
            window.clearInterval(this.get_car_gps_interval);
            this._super();
        }
    });

    var InfoWindow = Widget.extend({
        template: "baidu_map_rescue_vehicle_info_window",
        init: function (parent, id, enterprise_name, code, GPS_code, GPS_mobile, manager, manager_mobile, current_address,state,speed) {
            this.id = id;
            this.enterprise_name = enterprise_name;
            this.code = code;
            this.GPS_code = GPS_code;
            this.GPS_mobile = GPS_mobile;
            this.manager = manager;
            this.manager_mobile = manager_mobile;
            this.current_address = current_address;
            this.state = state;
            this.speed = speed;
            this._super(parent);
        },
        // events: {
        //     "click h4": function (e) {
        //         this.do_action({
        //             name: this.code,
        //             type: 'ir.actions.act_window',
        //             res_model: "tyibs.base.maintenance.rescue.vehicle",
        //             res_id: this.id,
        //             views: [[false, 'form']],
        //             target: 'current',
        //             context: {},
        //         })
        //     }
        // }
    });

    var RescueVehicleMapBtnBlock = Widget.extend({
        template: "tyibs-map-rescue-vehicle-btn-block",
        init: function (parent) {
            this._super(parent);
        },
        events: {
            "click button.tyibs-map-rescue-vehicle-btn": function (e) {
                this.trigger(e.target.value);
            }
        }
    });

    core.action_registry.add("lift_base.rescue_vehicle_map", RescueVehicleMap);
    core.form_tag_registry.add("rescue_vehicle_track_map", RescueVehicleTrackMap);
})